package com.live;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.logging.Logger;

public class Server {
    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workerGroup;
    public void start(){
        int bufferSize  =   128 * 1024;
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        bossGroup = new NioEventLoopGroup(4);
        workerGroup = new NioEventLoopGroup(availableProcessors * 2);
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.childOption(ChannelOption.SO_RCVBUF, bufferSize);
        bootstrap.childOption(ChannelOption.SO_SNDBUF, bufferSize);
        bootstrap.handler(new LoggingHandler(LogLevel.DEBUG));

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {

                ChannelPipeline pipeline = ch.pipeline();

                pipeline.addLast("Idle", new IdleStateHandler(30, 30, 40));

                pipeline.addLast("decode", new JSONDecoder(refParams.getPolicyFormat()));
                pipeline.addLast("encode", new JSONEncoder(refParams.getPolicyFormat()));

                pipeline.addLast(new PingHandler());
                pipeline.addLast(new PongHandler());

                pipeline.addLast("handler", refParams.getHandler());

            }
        });
    }
}
